package com.project.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

public class TokenSys {
    private  static final  long EXPIRE_TIME=1000*60*24;
    private static  final String TOKEN_SECRET="68a34f98-7fd7-4fb7-956a-def1e491b641";
    public static String createToken(String json){
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        String token= JWT.create().withHeader(header)
                .withClaim("info",json)
                .withExpiresAt(date).sign(algorithm);
        return token;
    }

    public static String verifierJwt(String token){
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        String info="";
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            DecodedJWT jwt = verifier.verify(token); //认证token
            info=jwt.getClaim("info").asString();//取token中的信息
        }catch (Exception e){
            return  "502";
        }
        return info;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(UUID.randomUUID());
    }
}
